package com.hrb.monkey.frament;


import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.hrb.commonsdk.okhttp.listener.DisposeDataListener;
import com.hrb.monkey.R;
import com.hrb.monkey.UserAdapter;
import com.hrb.monkey.network.http.RequestCenter;
import com.hrb.monkey.record.FirsFragmentRecord;
import com.hrb.monkey.record.User;
import com.hrb.monkey.record.bilicontentRecod;
import com.hrb.monkey.task.LoadInfoGson;
import com.hrb.monkey.utils.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class FirstFragment extends Fragment {

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.swipe_refresh)
    SmartRefreshLayout swipeRefresh;
    private Unbinder unbinder;
    LinearLayoutManager linearLayoutManager;
    private LoadInfoGson listLoad;

    private List<User> flist;
    UserAdapter madpter;

    private int lastPosition = 0;
    private int lastOffset = 0;

    public FirstFragment() {
        // Required empty public constructor
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_first, container, false);
        unbinder = ButterKnife.bind(this, view);
        linearLayoutManager = new LinearLayoutManager(getActivity());

        DividerItemDecoration dividerItemDecoration =
                new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);//分割线
        recyclerView.addItemDecoration(dividerItemDecoration);
        LinearLayoutManager layoutManager=new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        flist=new ArrayList<>();
         madpter=new UserAdapter(flist);
        recyclerView.setAdapter(madpter);
        /**
         * 记录recyclerView 在视图的位置添加滚动事件
         */
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(recyclerView.getLayoutManager() != null) {
                    getPositionAndOffset();
                }
            }
        });
        //加载数据
        postmessage( );
       // new LoadInfoGson(recyclerView, linearLayoutManager).execute("https://www.easy-mock.com/mock/5a4d85d3e5f9cd651a7fbe77/test/userInfo");
        //设置 Header 为 贝塞尔雷达 样式
        swipeRefresh.setRefreshHeader(new BezierRadarHeader(getContext()).setEnableHorizontalDrag(false).setPrimaryColor(0xD81B60).setAccentColor(0x33333));
//       WaterDropHeader waterDropHeader= new WaterDropHeader(getContext());
        // swipeRefresh.setRefreshHeader(waterDropHeader);
        //设置 Footer 为 球脉冲 样式
        swipeRefresh.setRefreshFooter(new BallPulseFooter(getContext()).setSpinnerStyle(SpinnerStyle.Scale));
        swipeRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
               // new LoadInfoGson(recyclerView, linearLayoutManager).execute("https://www.easy-mock.com/mock/5a4d85d3e5f9cd651a7fbe77/test/userInfo");
                swipeRefresh.finishRefresh(2000);
            }
        });
        swipeRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                postmessage( );
                //new LoadInfoGson(recyclerView, linearLayoutManager).execute("https://www.easy-mock.com/mock/5a4d85d3e5f9cd651a7fbe77/test/userInfo");
                swipeRefresh.finishLoadMore(2000);
            }
        });
        return view;
    }

    /**
     * 记录RecyclerView当前位置
     */
    private void getPositionAndOffset() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        //获取可视的第一个view
        View topView = layoutManager.getChildAt(0);
        if(topView != null) {
            //获取与该view的顶部的偏移量
            lastOffset = topView.getTop();
            //得到该View的数组位置
            lastPosition = layoutManager.getPosition(topView);
        }
    }

    /**
     * 让RecyclerView滚动到指定位置
     */
    private void scrollToPosition() {
        if(recyclerView.getLayoutManager() != null && lastPosition >= 0) {
            ((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(lastPosition, lastOffset);
        }
    }
    private void postmessage( ){

        RequestCenter.getRequest("https://www.easy-mock.com/mock/5a4d85d3e5f9cd651a7fbe77/test/userInfo", null, new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                FirsFragmentRecord user=(FirsFragmentRecord) responseObj;
                ToastUtil.show("本次更新"+user.data.size()+"条记录");
                if (user != null && user.data.size() > 0) {
                    flist.addAll(user.data);
                    UserAdapter  adapter=new UserAdapter(flist);
                    //madpter.setUserList(flist);
                    recyclerView.setAdapter(madpter);
                    scrollToPosition();
                }

            }

            @Override
            public void onFailure(Object reasonObj) {

            }
        },FirsFragmentRecord.class);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onResume() {
        super.onResume();
        SharedPreferences preferences= getActivity().getSharedPreferences("userInfo",Context.MODE_PRIVATE);
        //ToastUtil.show(preferences.getString("username","这个是默认值"));
    }
}
